using System;
using System.Collections.Generic;
using UnityEngine;

public class UIMgr : MonoSingleton<UIMgr>
{
    public RectTransform layerUI;
    public Dictionary<string, BaseView> viewsMap = new Dictionary<string, BaseView>();
    protected override void AutoInit()
    {

    }

    public void Open<T>(params object[] _params) where T : BaseView
    {
        var viewName = typeof(T).Name;
        if (!viewsMap.ContainsKey(viewName))
        {
            var view = Activator.CreateInstance(typeof(T)) as BaseView;
            var request = Resources.LoadAsync<GameObject>("Prefabs/UI/" + viewName);
            request.completed += (operation) =>
            {
                var instance = Instantiate(request.asset as GameObject, layerUI);
                view.gameObject = instance;
                viewsMap.Add(viewName, view);
                view.Init();
                view.Show();
            };
        }
    }

    public void Close<T>() where T : BaseView
    {
        var viewName = typeof(T).Name;
        if (viewsMap.ContainsKey(viewName))
        {
            var view = viewsMap[viewName];
            view.Hide();
            view.Dispose();
            viewsMap.Remove(viewName);
            Destroy(view.gameObject);
        }
    }

    public void Close(string viewName)
    {
        if (viewsMap.ContainsKey(viewName))
        {
            var view = viewsMap[viewName];
            view.Hide();
            view.Dispose();
            viewsMap.Remove(viewName);
            Destroy(view.gameObject);
        }
    }

    public void CloseAll()
    {
        foreach (BaseView view in viewsMap.Values)
        {
            Close<BaseView>();
        }
    }

    void Update()
    {
        foreach (BaseView view in viewsMap.Values)
        {
            view.Update(Time.deltaTime);
        }
    }
}